<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\WorkShopCollection;
use App\Http\Resources\WorkShopResource;
use App\model\Workshop;
use App\Repository\WorkShopRepository;
use App\Repository\WorkShopZSRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Carbon\Carbon;
use App\BrowseRecords;
use App\UserSearch;

class WorkshopZSController extends Controller
{
    public function index(Request $request,WorkShopZSRepository $workShopZSRepository,$type){
        $request=$request->all();
        $request['type']=$type;
        /*$user_id = auth('api')->id();
        if(isset($request['search_key'])&&$request['search_key']!=''&&isset($user_id)){
            $now = Carbon::now();
            UserSearch::updateOrCreate(['user_id'=>$user_id,'search_key'=>$request['search_key']],['updated_at'=>$now]);
        }*/
        $workShopList=$workShopZSRepository->getList($request);
        return new WorkShopCollection($workShopList);
    }
    public function detail($workshop_id,WorkShopRepository $workShopRepository){
/*        $salts = md5($_SERVER["REMOTE_ADDR"].$_SERVER['HTTP_USER_AGENT']);
        $now = Carbon::now();
        if(ClickHis::where('salts','=',$salts)->where('workshop_id','=',$workshop_id)->first()){
            if(ClickHis::where('salts','=',$salts)->where('workshop_id','=',$workshop_id)->where('updated_at','<',$now->subHour())->first()) {
                $workshopSave = Workshop::find($workshop_id);
                $workshopSave->click_count += 1;
                $workshopSave->save();
                ClickHis::where('salts','=',$salts)->where('workshop_id','=',$workshop_id)->update(['updated_at'=>$now->addHour()]);
            }
        }else{
            $workshopSave = Workshop::find($workshop_id);
            $workshopSave->click_count += 1;
            $workshopSave->save();
            $clickHis = new ClickHis;
            $clickHis->workshop_id = $workshop_id;
            $clickHis->salts = $salts;
            $clickHis->save();
        }*/
        $workshop=$workShopRepository->detail($workshop_id);
        $workshop['rent_count']=Workshop::where('park_id',$workshop['park_id'] ?? 0)->where('type',0)->count('id') ;
        $workshop['buy_count']=Workshop::where('park_id',$workshop['park_id'] ?? 0)->where('type',1)->count('id') ;
        $user_id = auth('api')->id();
        if(isset($user_id)){
            $workshops = Workshop::find($workshop_id);
            $title = $workshops->title;
            $logo = $workshops->logo;
            $now = Carbon::now();
            BrowseRecords::updateOrCreate(['user_id'=>$user_id,'produce_id'=>$workshop_id,'type'=>0],
                ['user_name'=>User::find($user_id)->name,'title'=>$title,'logo'=>$logo,'updated_at'=>$now]);
        }
        return new  WorkShopResource($workshop);
    }
}
